package io.esirong.util;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Base64;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;

/**
 * 常用加密解密，编码解码
 * <p>Base64 SHA1
 */
public class Encode {

    public static String sHA1(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), PackageManager.GET_SIGNATURES);
            byte[] cert = info.signatures[0].toByteArray();
            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] publicKey = md.digest(cert);
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < publicKey.length; i++) {
                String appendString = Integer.toHexString(0xFF & publicKey[i])
                        .toUpperCase(Locale.US);
                if (appendString.length() == 1) {
                    hexString.append("0");
                }
                hexString.append(appendString);
                hexString.append(":");
            }
            String result = hexString.toString();
            return result.substring(0, result.length() - 1);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * Base64解码
     *
     * @param base64Str 将要解码的Base64字串
     * @return 解码后的byte[]
     */
    public static byte[] enBase64(String base64Str) {
        //一些去头处理（作健状性代码）
        base64Str = base64Str.replace("", "")
                .replace("data:image/jpg;base64,", "")
                .replace("data:image/png;base64,", "")
                .replace("data:image/jpeg;base64,", "");

        return Base64.decode(base64Str, Base64.DEFAULT);
    }

    /**
     * Base64编码 成String
     *
     * @param data 将被编码的byte[]
     * @return 字符串
     */
    public static String deBase64(byte[] data) {
        String strBase64 = Base64.encodeToString(data, Base64.DEFAULT);
        return strBase64;
    }
}
